package com.lzb.web.controller;

import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.lzb.cache.SessionCached;
import com.lzb.common.constant.CommonConstantValues;
import com.lzb.common.constant.favourite.ConstantValues;
import com.lzb.common.easyui.datagrid.DataGridDTO;
import com.lzb.common.easyui.datagrid.DataGridJsonDTO;
import com.lzb.common.helper.redis.RedisHelper;
import com.lzb.common.model.JsonDTO;
import com.lzb.model.MngMomentModel;
import com.lzb.model.MngUserModel;
import com.lzb.service.FavouriteService;
import com.lzb.service.MngMomentService;
import com.lzb.service.MngUserService;

@Controller
@RequestMapping(value = "/")
public class SiteController extends BaseController {
	
	//暂时采用ConcurrentHashMap缓存session({sessionId, MngUserModel})
	@Resource(name = SessionCached.BEAN_PACKAGE_NAME)
	private SessionCached cachedSession;
	
	@Resource(name = MngMomentService.BEAN_PACKAGE_NAME)
	private MngMomentService mngMomentService;
	
	@Resource(name = MngUserService.BEAN_PACKAGE_NAME)
	private MngUserService mngUserService;
	
	@Resource(name = FavouriteService.BEAN_PACKAGE_NAME)
	private FavouriteService favouriteService;
	
	@Autowired
	private RedisHelper redisHelper;
	
	@Value("${session.timeout.seconds}")
	private int sessionTimeoutSeconds;
	
	@RequestMapping(value = "login")
	public String login() {
		return "/login";
	}
	
	@RequestMapping(value = "doNotNeedSecurityToShowCommonMomentList")
	public String doNotNeedSecurityToShowCommonMomentList() {
		return "/common_moment";
	}
	
	@RequestMapping(value = "doNotNeedSecurityDoShowCommonMomentList")
	@ResponseBody
	public JsonDTO doNotNeedSecurityDoShowCommonMomentList(MngMomentModel queryModel, HttpServletRequest request) {
		JsonDTO json = new JsonDTO();
		DataGridDTO pager = DataGridDTO.newInstance(request);
		queryModel.setDataGridDTO(pager);
		DataGridJsonDTO result = mngMomentService.query(queryModel);
		json.setMsg("查询成功");
		json.setSuccess(true);
		json.setObj(result);
		return json;
	}
	
	@RequestMapping(value = "doAddMoment") 
	@ResponseBody
	public JsonDTO doAddMoment(MngMomentModel moment, HttpServletRequest request) {
		JsonDTO json = new JsonDTO();
		String momentUUID = mngMomentService.add(moment);
		//key:userUUID values:[{momentUUID, float(createDate+createTime)}]
		favouriteService.doAddUserMoment(cachedSession.get(request.getSession().getId()).getUuid(), momentUUID, new BigDecimal(moment.getCreateDate() + moment.getCreateTime()).doubleValue());
		json.setMsg("添加成功");
		json.setSuccess(true);
		return json;
	}
	
	@RequestMapping(value = "doNotNeedSecurityLogin") 
	@ResponseBody
	public JsonDTO doNotNeedSecurityLogin(MngUserModel user, HttpServletRequest request) {
		JsonDTO json = new JsonDTO();
		user = mngUserService.login(user);
		if(user == null) {
			json.setMsg("登陆失败");
			json.setSuccess(false);
		} else {
			String projectName = request.getContextPath();
			HttpSession session = request.getSession();
			cachedSession.put(session.getId(), user);
			session.setMaxInactiveInterval(sessionTimeoutSeconds);
			//在前端页面跳转到用户的朋友圈管理界面
			json.setObj(projectName + "/toShowUserMomentList.do");
			json.setMsg("登陆成功");
			json.setSuccess(true);
		}
		return json;
	}
	
	@RequestMapping(value = "toShowUserMomentList")
	public ModelAndView toShowUserMomentList(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("currentLoginedUser", cachedSession.get(request.getSession().getId()));
		mav.setViewName("/user_moment");
		return mav;
	}
	
	@RequestMapping(value = "doShowUserMomentList") 
	@ResponseBody
	public DataGridJsonDTO doShowUserMomentList(HttpServletRequest request) {
		DataGridJsonDTO result = new DataGridJsonDTO();
		String userUUID = cachedSession.get(request.getSession().getId()).getUuid();
		DataGridDTO pager = DataGridDTO.newInstance(request);
		Set<String> momentUUIDset = favouriteService.doGetUserMomentsByRange(userUUID, pager.getStartIndex(), pager.getStartIndex() + pager.getRows() - 1);
		if(null != momentUUIDset && momentUUIDset.size() != 0) {
			List<MngMomentModel> mngMomentModelLst = new LinkedList<MngMomentModel>();
			for(String _momentUUID : momentUUIDset) {
				MngMomentModel _model = JSON.parseObject(redisHelper.get(ConstantValues.DOMAIN_MOMENT + CommonConstantValues.REDIS_SPLITTER + _momentUUID), MngMomentModel.class);
				//该朋友圈点赞的用户
				Set<String> favouritedUserUUIDs = favouriteService.doGetFavouritesByScoreDesc(_momentUUID, 0, -1);
				List<MngUserModel> favouritedUsers = mngUserService.getMngUsersByUUIDs(favouritedUserUUIDs.toArray(new String[favouritedUserUUIDs.size()]));
				//关联点赞用户的信息
				_model.setFavouriedMngUserModels(favouritedUsers);
				mngMomentModelLst.add(_model);
			}
			result.setRows(mngMomentModelLst);
			result.setTotal(favouriteService.doGetUserMomentsCount(userUUID));
			return result;
		}
		return result;
	}
	
	@RequestMapping(value = "deleteMoment")
	@ResponseBody
	public JsonDTO deleteMoment(String momentUUID, String userUUID){
		JsonDTO result = new JsonDTO();
		mngMomentService.delete(momentUUID);
		favouriteService.doDeleteMoment(userUUID, momentUUID);
		result.setSuccess(true);
		result.setMsg("删除朋友圈成功");
		return result;
	}
	
	/**
	 * 用户退出
	 * */
	@RequestMapping("/doNotNeedSecurityLogout")
	@ResponseBody
	public JsonDTO doNotNeedSecurityLogout(HttpServletRequest request) {
		JsonDTO retJson = new JsonDTO();
		cachedSession.remove(request.getSession().getId());
		request.getSession().invalidate();
		retJson.setSuccess(true);
		retJson.setObj(request.getContextPath() + "/login.jsp");
		return retJson;
	}
	
	/**
	 * 主页获取最新的20条朋友圈
	 * */
	@RequestMapping("/doNotNeedSecurityGetTheNewestMoment")
	@ResponseBody
	public JsonDTO doNotNeedSecurityGetTheNewestMoment() {
		JsonDTO retJson = new JsonDTO();
		List<MngMomentModel> rows = new LinkedList<MngMomentModel>();
		List<String> theNewestMomentUUIDs = favouriteService.doGetTheNewestMoment();
		if(theNewestMomentUUIDs != null && 0 != theNewestMomentUUIDs.size()) {
			for(int i=0; i<theNewestMomentUUIDs.size(); i++) {
				String _momentUUID = theNewestMomentUUIDs.get(i);
				MngMomentModel _model = JSON.parseObject(redisHelper.get(ConstantValues.DOMAIN_MOMENT + CommonConstantValues.REDIS_SPLITTER + _momentUUID), MngMomentModel.class);
				if(_model != null) {
					//该朋友圈点赞的用户
					Set<String> favouritedUserUUIDs = favouriteService.doGetFavouritesByScoreDesc(_momentUUID, 0, -1);
					List<MngUserModel> favouritedUsers = mngUserService.getMngUsersByUUIDs(favouritedUserUUIDs.toArray(new String[favouritedUserUUIDs.size()]));
					_model.setFavouriedMngUserModels(favouritedUsers);
					rows.add(_model);
				}
			}
			retJson.setObj(rows);
			retJson.setSuccess(true);
		}
		return retJson;
	}
	
	@RequestMapping("/favourite")
	@ResponseBody
	public JsonDTO favourite(String momentUUID, HttpServletRequest request) {
		String currentLoginedUserUUID = cachedSession.get(request.getSession().getId()).getUuid();
		favouriteService.doAddUserFavourite(currentLoginedUserUUID, momentUUID, new BigDecimal(LocalDateTime.now().toString("yyyyMMddHHmmssSSS")).doubleValue());
		JsonDTO retJson = new JsonDTO();
		retJson.setSuccess(true);
		return retJson;
	}
	
}
